package com.example.lazylist;

import java.util.List;

import com.example.db.TestDB;
import com.example.model.Test;
import com.example.test.DBActivity;
import com.example.test.R;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class LazyAdapter extends BaseAdapter{
	private static String TAG = "DBActivity";
	private DBActivity activity;
	private List<Test> data;
	private static LayoutInflater inflater = null;
	public ImageLoader imageLoader;
	
	private TestDB test_db;
	public LazyAdapter(DBActivity a, List d,TestDB db) {
		activity = a;
		data = d;
		test_db = db;
		inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		imageLoader = new ImageLoader(activity.getApplicationContext());
	}

	public int getCount() {
		return data.size();
	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		final Test test = data.get(position);

		View view = convertView;
		if (convertView == null)//性能优化
			view = inflater.inflate(R.layout.test_news, null);
		
		view.findViewById(R.id.test_news_tv_delete).setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				String id = test.getId()+"";
				test_db.delecte(id);
				Log.i(TAG, "删除:"+id);
				data = test_db.all();
				activity.reload(data);
			}
		});		
		TextView title = (TextView) view.findViewById(R.id.test_news_tv_title);
		TextView comment = (TextView) view.findViewById(R.id.test_news_tv_comment);
		ImageView img = (ImageView) view.findViewById(R.id.test_news_imgv_img);

		String strTitle = test.getId()+"==========================";
		if (TextUtils.isEmpty(strTitle)) {
			title.setText("");
		} else {
			title.setText(strTitle);
		}

		String strComment = "评论：" + test.getComment();
		comment.setText(strComment);

		String strUrl = test.getImg();
		if (TextUtils.isEmpty(strUrl)) {
			img.setImageResource(R.drawable.ic_l_test);
		} else {
			// 改用lazylist
			ImageView image = BaseViewHolder.get(view, R.id.test_news_imgv_img);
			imageLoader.DisplayImage(test.getImg(), image);
		}
		return view;
	}
	
	/*
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.test_news_tv_delete:
			//删除操作
			String id = test.getId()+"";
			test_db.delecte(id);
			Log.i(TAG, "删除:"+id);
			data = test_db.all();
			activity.reload(data);
			break;

		default:
			break;
		}
	}*/
}